var express = require('express');
var router = express.Router();
const mongoose = require("mongoose");
docBaseConnection = mongoose.createConnection("mongodb://127.0.0.1:27017/docBase");
// const mongoose = require("mongoose");
commomConnection = mongoose.createConnection("mongodb://127.0.0.1:27017/demo_oj");
var roomCodeSchema = require("../schema/roomCode")
var docSchema = require("../schema/doc")

// 清除coeditor的数据库缓存
// param:
//    dropCollections: Array 要清除的doc名字数组，格式如 rommid/userid/problem_id
router.post("/clearMany", function (req, res, next) {
    let global_error = undefined
    // 获取cllectionName 即协同编辑的docName
    let collections = req.body.params.dropCollections
    // dropCollection = rommid/userid/problem_id
    for (let collection of collections) {
        console.log(collection);
        let praseCollection = collection.split('/')[0] + '/' + collection.split('/')[2]
        docBaseConnection.dropCollection(
            praseCollection,
            (err, result) => {
                if (err) {
                    console.log(err)
                    global_error = err
                }
                else {
                    console.log(praseCollection, " Collection droped");
                }
            }
        );
        praseCollection = 'o_' + praseCollection
        docBaseConnection.dropCollection(
            praseCollection,
            (err, result) => {
                if (err) {
                    console.log(err)
                    global_error = err
                }
                else {
                    console.log(praseCollection, " Collection droped");
                }
            }
        );
    }
    if (global_error) {
        res.json({
            status: 0,
            msg: global_error.message,
            result: {
            }
        })
    } else {
        res.json({
            status: 1,
            msg: "clear all",
            result: {},
        })
    }

});


// 转移coeditor的数据库缓存
// param:
//    docNames: Array 要转移的doc名字数组，格式如 rommid/userid/problem_id
router.post("/moveMany", (req, res, next) => {
    docNames = req.body.params.docNames
    let global_error = undefined

    for (let docName of docNames) {
        let user_id, code, m;//= "author0"
        console.log(docName.split('/')[0])
        console.log(docName.split('/')[0] + '/' + docName.split('/')[2])

        let praseDocName = docName.split('/')[0] + '/' + docName.split('/')[2];
        // let param = undefined;
        // let docName = ["roomid/user/0"];
        let docModel = docBaseConnection.model(praseDocName, docSchema);
        console.log(docModel)
        docModel.findOne((err, doc) => {
            if (err) {
                console.log(err)
                global_error = err
            }
            else {
                if (doc) {// doc存在读出doc信息存入param
                    user_id = doc._id;
                    code = doc.code;
                    m = doc._m;
                    let param = {
                        m: m,
                        room_id: docName.split('/')[0],
                        user_id: docName.split('/')[1],
                        problem_id: docName.split('/')[2],
                        code: code,
                    }
                    // doc信息存入RoomCode数据库
                    let roomCodeModel = commomConnection.model("RoomCode", roomCodeSchema);
                    new roomCodeModel(param, false)
                        .save(err => {
                            if (err) {
                                console.log(err)
                                global_error = err
                            }
                            else {
                                console.log("save success!");
                                // res.json({
                                //     status: "1",
                                //     msg: '',
                                //     result: {
                                //         param: param,
                                //     }
                                // });
                            }
                        })
                }
                else {// 不存在doc 可能已被请理
                    console.log("not exsist")
                    global_error = Object()
                    global_error.message = "not exsist"
                }
            }
        });
    }

    // 将param存入
    if (global_error) {
        res.json({
            status: "0",
            msg: 'move failed',
            result: {

            }
        });
    } else {
        res.json({
            status: "1",
            msg: 'move success',
            result: {

            }
        });

    }

})

router.get("/getCode",(req,res,next)=>{
    var pid = Object(req.query.pid)
    var rid = Object(req.query.rid)
    var uid = Object(req.query.uid)

    let codeDB = commomConnection.model("RoomCode", roomCodeSchema);
    if(req.session.user&& req.session.user.status === 1){
        codeDB.findOne({
            problem_id:pid,
            user_id:uid,
            room_id:rid,
        }).then(function(data,err){
            if(err){
                res.json({
                    status: '500',
                    msg: err.message,
                    result: {}
                });
            }
            else{
                if(data){
                    res.json({
                        status: "1",
                        msg: '',
                        result: {
                            code:data.code
                        }
                    });
                }
                else{
                    res.json({
                        status: "0",
                        msg: 'not found',
                        result: {
                            code:''
                        }
                    });
                }
            }
        })
    }else{
        res.json({
            status: "2",
            msg: 'Insufficient permission',
            result: {}
        });
    }
})

module.exports = router;